//
//  Status.swift
//  XNWeiBo_Swift
//
//  Created by xunan on 2016/12/1.
//  Copyright © 2016年 xunan. All rights reserved.
//

import UIKit
import SDWebImage

class Status: NSObject {
    var created_at: String? {
        didSet {
            let createdDate = NSDate.dateWithStr(created_at!)
            created_at = createdDate.descDate
        }
    }
    var id: Int = 0
    var text: String?
    var source: String? {
        didSet {
            if let str = source {
                if str == "" {
                    return
                }
                // 获取开始截取的位置
                let startLocation = (str as NSString).rangeOfString(">").location + 1
                // 截取长度
                let length = (str as NSString).rangeOfString("<", options: NSStringCompareOptions.BackwardsSearch).location - startLocation
                source = "来自:" + (str as NSString).substringWithRange(NSMakeRange(startLocation, length))
            }
        }
    }
    
    /// 配图数组
    var pic_urls: [[String: AnyObject]]? {
        didSet {
            // 1.初始化数组
            storedPicURLS = [NSURL]()
            storedLargePicURLS = [NSURL]()
            for dict in pic_urls! {
                if let urlStr = dict["thumbnail_pic"] as? String {
                    // 将字符串转为URL保存到数组中
                    storedPicURLS?.append(NSURL(string: urlStr)!)
                    
                    // 处理大图数据
                    let largeURLStr = urlStr.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                    storedLargePicURLS?.append(NSURL(string: largeURLStr)!)
                }
            }
        }
    }
    
    // 保存当前微博所有配图的URL
    var storedPicURLS: [NSURL]?
    // 保存当前微博所有配图的大图URL
    var storedLargePicURLS: [NSURL]?
    
    // 用户信息
    var user: User?
    
    // 转发微博
    var retweeted_status: Status?
    
    // 如果有转发, 原创就没有配图
    // 定义一个计算属性, 用于返回原创获取转发配图的URL数组
    var pictureURLS:[NSURL]? {
        return retweeted_status != nil ? retweeted_status?.storedPicURLS : storedPicURLS
    }
    
    // 原创或者或者转发的大图数组
    var LargePictureURLS:[NSURL]? {
        return retweeted_status != nil ? retweeted_status?.storedLargePicURLS : storedLargePicURLS
    }
    
    class func loadStatusses(since_id: Int, max_id: Int, finished: (models:[Status]?, error:NSError?)->()) {
        
        
        
        
        let path = "2/statuses/home_timeline.json"
        var params = ["access_token": UserAccount.loadAccount()!.access_token!]
                
        // 下拉刷新
        if since_id > 0 {
            params["since_id"] = "\(since_id)"
        }
        // 上拉刷新
        if max_id > 0 {
            params["max_id"] = "\(max_id - 1)"
        }
        
        NetworkTools.shareNetworkTools().GET(path, parameters: params, success: { (_, JSON) in
            
            StatusDAO.cacheStatuses(JSON!["statuses"] as! [[String: AnyObject]])
            
            let models = dict2Model(JSON!["statuses"] as! [[String: AnyObject]])
            
            cacheStatusImages(models, finished: finished)
            
            
            }) { (_, error) in
                print(error)
                finished(models: nil, error: error)
        }
        
    }
    
    /// 缓存配图
    class func cacheStatusImages(list: [Status], finished: (models:[Status]?, error:NSError?) ->()) {
       
        if list.count == 0 {
            finished(models: list, error: nil)
        }
        
        // 创建一个组
        let group = dispatch_group_create()
        
        for status in list {
            // Swift2.0新语法, 如果条件为nil, 那么就执行else后面的语句
            guard status.storedPicURLS != nil else {
                continue
            }
            for url in status.storedPicURLS! {
                // 将当前下载操作添加到组中
                dispatch_group_enter(group)
                
                // 缓存图片
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) -> Void in
                    
                    // 离开当前组
                    dispatch_group_leave(group)
                })
            }
        }
        
        // 2.当所有图片都下载完毕再通过闭包通知调用者
        dispatch_group_notify(group, dispatch_get_main_queue()) { 
            finished(models: list, error: nil)
        };
        
    }
    
    class func dict2Model(list: [[String: AnyObject]]) -> [Status] {
        var models = [Status]()
        for dict in list
        {
            models.append(Status(dict: dict))
        }
        return models
    }
    
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        // 1.判断当前是否正在给微博字典中的user字典赋值
        if "user" == key
        {
            user = User(dict: value as! [String : AnyObject])
            return
        }
        
        // 2.判断是否是转发微博, 如果是就自己处理
        if "retweeted_status" == key {
            retweeted_status = Status(dict: value as! [String : AnyObject])
            return
        }
        
        // 3.调用父类方法, 按照系统默认处理
        super.setValue(value, forKey: key)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    // 打印当前模型
    var prpperties = ["created_at", "id", "text", "source", "pic_urls"]
    override var description: String {
        let dict = dictionaryWithValuesForKeys(prpperties)
        return"\(dict)"
    }
}






































